package com.pactera.bledemo.activity.ble

import android.bluetooth.BluetoothClass
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.dylanc.viewbinding.nonreflection.binding
import com.pactera.bledemo.databinding.ActivityClientDetailBinding
import com.pactera.library.bluetooth.BleManager
import com.pactera.library.bluetooth.event.BleManagerEvent
import com.pactera.library.listener.BleNotifyCallback
import com.pactera.library.listener.BleReadCallback
import com.pactera.library.listener.ConnectManagerCallback
import com.pactera.library.utils.SerialDataUtils
import com.pactera.library.utils.ToastUtil

class BLEDetailActivity : AppCompatActivity() {
    private val binding by binding(ActivityClientDetailBinding::inflate)

    val ble = BleManager.getInstance(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val name = intent.getStringExtra("name")
        val address = intent.getStringExtra("address")
        binding.apply {
            actionToolbar.tvTitle.text = name
            actionToolbar.imgBack.setOnClickListener { finish() }
            text.text = "名称：$name \nmac：$address"
        }


        binding.apply {
            btnConnect.setOnClickListener {
                ble.connect(address, connectCallback)
            }

            btnWrite.setOnClickListener {
                //val text = content.toByteArray(charset("utf-8"))
                //val text = "我是移动端发送过去的数据".toByteArray(charset("utf-8"))

                // val cmd = "A50F001000"
                val cmd =
                    "13  16    01 00 00 00     00 00 00 00    03 00 00 00    00 00 00 00     FFFF"
                //val cmd = "13  10  01 00 00 00   00 00 00 00"
                ble.sendData(cmd)
            }


            btnRead.setOnClickListener {
                ble.readData(object : BleReadCallback {
                    override fun onReadSuccess(
                        dedvice: BluetoothDevice?,
                        characteristic: BluetoothGattCharacteristic?
                    ) {
                        runOnUiThread {
                            val bytes = characteristic?.value
                            val receiveString = SerialDataUtils.ByteArrToHex(bytes).trim()
                            println("btnRead BleManager.readCharacteristic receiveString=$receiveString")
                        }

                    }

                    override fun onReadFailed(device: BluetoothDevice?, failedCode: Int) {
                        println("BLEDetailActivity.onReadFailed failedCode=$failedCode")
                    }

                });
            }
        }
    }

    private fun notifyCallback(): BleNotifyCallback {
        return object : BleNotifyCallback {
            override fun onChanged(
                device: BluetoothDevice,
                characteristic: BluetoothGattCharacteristic
            ) {
                runOnUiThread {
                    val bytes = characteristic.value
                    val receiveString = SerialDataUtils.ByteArrToHex(bytes).trim()
                    println("notifyCallback BleManager.readCharacteristic receiveString=$receiveString")

                    binding.tvText.append("$receiveString\n")
                }
            }


        }
    }

    val connectCallback = object : ConnectManagerCallback {
        override fun onConnectionChanged(bleEvent: BleManagerEvent) {
            runOnUiThread {
                if (bleEvent!!.isConnected) {
                    binding.tvTextConnect.append("已连接\n")
                    println("BLEDetailActivity.onConnectionChanged 已连接  device=${bleEvent?.device?.address}")
                } else if (bleEvent!!.isConnecting) {
                    println("BLEDetailActivity.onConnectionChanged 连接中...")
                    binding.tvTextConnect.append("连接中...\n")
                } else if (bleEvent!!.isDisconnected) {
                    binding.tvTextConnect.append("未连接\n")
                    println("BLEDetailActivity.onConnectionChanged 未连接")
                } else if (bleEvent!!.isReconnection) {
                    binding.tvTextConnect.append("尝试重连中\n")
                    println("BLEDetailActivity.onConnectionChanged 尝试重连中")
                }
            }

        }

        override fun onServicesDiscovered(gatt: BluetoothGatt) {
            println("BLEDetailActivity.onServicesDiscovered ")
        }

        override fun onConnectFailed(errorMsg: String, errorCode: Int) {
            println("BLEDetailActivity.onServicesDiscovered  errorMsg=$errorMsg errorCode=$errorCode")
        }

        override fun onReady(device: BluetoothDevice) {
            println("BLEDetailActivity.onReady 连接成功，已做好准备 device.address=${device.address}")
            ble.setCharacteristicNotification(notifyCallback(), true)
        }


    }

    override fun onDestroy() {
        super.onDestroy()
        ble.closeConnect()
    }


}